<?php
/**
 * Created by PhpStorm.
 * User: zng
 * Date: 2020/3/25
 * Time: 14:36
 */
namespace app\api\service\order;

use app\api\model\order\Order as OrderModels;
use app\exceptions\OrdinaryException;
use think\Db;
use app\api\service\order\ShoppingCart;

Class Order{

    /**
     * 开始下单
     * @param array $data
     * @param mixed $shopping
     * @param float $distribution_fee
     * @param mixed $address
     * @throws OrdinaryException
     * @return array
     */
    public function setOrder(array $data, $shopping, $distribution_fee, $address)
    {
        $orderNumber = date("YmdHis").rand(1000,9999);
        Db::startTrans();
        $order = OrderModels::create([
            'order_number' => $orderNumber,
            'price' => $data['price'],
            'distribution_fee' => $distribution_fee,
            'remarks' => $data['remarks'],
            'username' => $address->username,
            'area' => $address->area,
            'mobile' => $address->mobile,
            'address' => $address->address
        ]);
        if ( ! $order->id ) {
            Db::rollback();
            throw new OrdinaryException('下单失败!请重试');
        }
        $orderFoods = array_map(function($v){
            return ['fid'=>$v['fid'],'food_title'=>$v['foods']['title'],'unit_price'=>$v['foods']['price'],'number'=>$v['number'],'pack_fee'=>$v['foods']['pack_fee']];
        },$shopping->toArray());
        $res = $order->orderFoods()->saveAll($orderFoods);
        if ( count($res) <= 0 ) {
            Db::rollback();
            throw new OrdinaryException('下单失败!请重试');
        }
        if ( false === (new ShoppingCart())->clean() ) {
            Db::rollback();
            throw new OrdinaryException('下单失败!请重试');
        }
        foreach ( $shopping as $key => $_shopping ) {
            $_shopping->foods->stock -= $_shopping->number;
            if ( ! $_shopping->foods->save() ) {
                Db::rollback();
                throw new OrdinaryException('库存删减失败,请重试');
            }
        }
        Db::commit();
        return [
            'order_number' => $orderNumber,
            'username' => $address->username
        ];
    }

    /**
     * 订单列表
     * @param array $get
     * @return mixed
     */
    public function lists(array $get)
    {
//        $pageSize = get($get,'pageSize')>0?$get['pageSize']:5;
        return OrderModels::with(['orderFoods'])->order('id', 'desc')->selectOrFail()->append(['handle_text']);
    }

    /**
     * 获取订单详情
     * @param int $id
     * @return mixed
     */
    public function read(int $id)
    {
        return OrderModels::with(['order_foods'=>function($query){
            $query->with(['foods']);
        }])->getOrFail($id);
    }

    /**
     * 取消订单
     * @param int $id
     * @return bool
     */
    public function cancel(int $id)
    {
        $order = OrderModels::with(['orderFoods'=>function($query){
            $query->with(['foods']);
        }])->getOrFail($id);
        if ( time()-strtotime($order->create_at) > 60*30 ) {
            throw new OrdinaryException('该订单已超过半小时,不可取消');
        }
        if ( $order->handle != 0 ) {
            throw new OrdinaryException('该订单状态已不可改变');
        }
        Db::startTrans();
        $order->handle = 2;
        $order->handle_at = date("Y-m-d H:i:s");
        if ( false === $order->save() ) {
            Db::rollback();
            throw new OrdinaryException('取消失败,请重试');
        }
        foreach ( $order->orderFoods as $_orderFoods ) {
            if ( $_orderFoods->foods->save(['stock'=>$_orderFoods->foods->stock+$_orderFoods->number]) === false ) {
                Db::rollback();
                throw new OrdinaryException('库存返还失败!请重试');
            }
        }
        Db::commit();
        return true;
    }

}